<template>
    <div id="app">
        <h3>单个图片上传</h3>
        <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :http-request="uploadRequest"
            :before-upload="beforeUpload"
        >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <h3>多个图片上传</h3>
        <el-upload
            class="avatar-uploader"
            action="#"
            multiple
            :auto-upload="false"
            :on-change="onChange"
        >
            <template v-if="imageUrlList.length>0">
                <img  :src="item" class="avatar" v-for="(item,index) in imageUrlList" :key="index" />
            </template>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-button @click="uploadRequestMultiple" type="primary">点击上传</el-button>
    </div>
</template>

<script>
import { upload, multipleUpload } from './api/index'
export default {
    name: 'App',
    data () {
        return {
            imageUrl: '',
            file: '',
            files: [],
            imageUrlList: []
        }
    },
    methods: {
        beforeUpload (file, fileList) {
            this.file = fileList
        },
        onChange (file, fileList) {
            this.files = fileList
        },
        uploadRequestMultiple () {
            const formdata = new FormData()
            this.files.forEach(item => {
                formdata.append('avatar', item.raw)
            })
            multipleUpload(formdata).then(res => {
                this.imageUrlList = res.data.url
            })
        },
        uploadRequest () {
            const formdata = new FormData()
            formdata.append('avatar', this.file)
            upload(formdata).then(res => {
                this.imageUrl = res.data.url
            })
        }
    }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
